import { JSX, useEffect, useState } from 'react'
import { Button, Input } from 'antd'

const AppCom = (): JSX.Element => {
  const [value, setValue] = useState<string>('')
  const [res, setRes] = useState<string>('')

  // 在组件加载时监听串口的返回数据
  useEffect(() => {
    // 监听 'serial:receive' 事件
    window.electron.ipcRenderer.on('serial:receive', (_, args) => {
      console.log('收到主进程发送的数据:', args)
      setRes(args.message) // 更新组件状态
    })

    // 在组件卸载时解除监听
    return () => {
      window.electron.ipcRenderer.removeAllListeners('serial:receive')
    }
  }, [])

  const handleClick = (): void => {
    window.electron.ipcRenderer.invoke('serial:send', { input: value }).then((res) => {
      console.log(res)
    })
  }

  const oninput = (e): void => {
    setValue(e.target.value)
  }

  return (
    <div>
      <div
        style={{
          display: 'flex',
          gap: '20px'
        }}
      >
        <Input value={value} onInput={oninput}></Input>
        <Button onClick={handleClick}>发送</Button>
      </div>
      <div>{res}</div>
    </div>
  )
}

export default AppCom
